from django.shortcuts import render

# Create your views here.
# 对日志调用
import logging

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

import models
from constants import NAV_HEADER, NAV_FOOTER, NAV_HEADER_SIZE, NAV_FOOTER_SIZE, BANNER_SIZE
from views import CacheListAPIView
from .models import Nav, Banner, Category
from .serializers import NavModelSerializer, BannerModelSerializer, CategorySerializer

logger = logging.getLogger("django")

# Create your views here.
class HomeAPIView(APIView):
    def get(self,request):
        """测试代码，测试完成以后将来可以删除"""
        # 测试日志功能
        # logger.error("error信息")
        # logger.info("info信息")
        # 读取redis数据
        redis = get_redis_connection("sms_code")
        brother = redis.lrange("brother", 0, -1)
        return Response(brother, status.HTTP_200_OK)

class NavHeaderListAPIView(CacheListAPIView):
    """顶部导航视图"""
    queryset = Nav.objects.filter(position=NAV_HEADER, is_show=True, is_deleted=False).order_by("orders", "-id")[:NAV_HEADER_SIZE]
    serializer_class = NavModelSerializer


class NavFooterListAPIView(CacheListAPIView):
    """脚部导航视图"""
    queryset = Nav.objects.filter(position=NAV_FOOTER, is_show=True, is_deleted=False).order_by("orders", "-id")[:NAV_FOOTER_SIZE]
    serializer_class = NavModelSerializer

class BannerListAPIView(CacheListAPIView):
    """轮播广告视图"""
    queryset = Banner.objects.filter(is_show=True, is_deleted=False).order_by("orders", "-id")[:BANNER_SIZE]
    serializer_class = BannerModelSerializer

# 首页分类
class CategoryView(APIView):
    def get(self, request):
        allcate=Category.objects.filter(parent=None,ishome=True,is_show=True).order_by('orders')
        ser=CategorySerializer(allcate,many=True)
        for i in ser.data:
            i['children']=i['children'][:3]
        return Response({"msg":"ok","data":ser.data,"code":200})

# 分类详情
class CategoryDetailView(APIView):
    def get(self,request):
        id=request.GET.get("id")
        info=Category.objects.filter(id=id,is_show=True,ishome=True,parent=None).first()
        ser=CategorySerializer(info)
        return Response({"msg":"ok","data":ser.data,"code":200})
